<template>
  <div class="center">
    <!-- 商品类型 -->
    商品类型:&ensp;
    <el-input v-model="category" style="width: 470px" placeholder="请输入商品分类编号" />
    <br />

    <!-- 商品名称 -->
    商品名称:&ensp;
    <el-input v-model="name" style="width: 470px" placeholder="请输入商品名称" class="ipt1" />
    <br />

    <!-- 商品详情 -->
    详情描述:&ensp;
    <el-input v-model="desc" style="width: 470px" placeholder="请输入具体的详情描述" class="ipt1" />
    <br />

    <!-- 上传图片链接 -->
    上传图片链接:&ensp;
    <el-input v-model="link" style="width: 470px" placeholder="请输入上传图片的链接" class="ipt1" />
    <br />

    <!-- 上传图片网址 -->
    上传图片网址:&ensp;
    <el-input v-model="url" style="width: 470px" placeholder="请输入上传图片的网址" class="ipt1" />
    <br />

    <!-- 图片封面 -->
    图片封面:&ensp;
    <el-input v-model="coverImage" style="width: 470px" placeholder="请上传图片封面" class="ipt1" />
    <br />

    <!-- 图片墙组件 -->
    <el-upload
      v-model:file-list="fileList"
      action="http://localhost:1337/api/v1/admin/productcategory"
      name="img"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      id="img"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <br />

    <!-- 预览弹框 -->
    <el-dialog v-model="dialogVisible">
      <img w-full :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
    <br />

    <!-- 发布按钮 -->
    <el-button type="primary" class="btn" @click="add">发布</el-button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { addRequest } from '@/api/lunbo'

const category = ref('')
const name = ref('')
const desc = ref('')
const link = ref('')
const url = ref('')
const coverImage = ref('')
const fileList = ref([])
const dialogVisible = ref(false)
const dialogImageUrl = ref('')

// 处理图片预览
function handlePictureCardPreview(file) {
  dialogImageUrl.value = file.url || file.response?.fileUrl
  dialogVisible.value = true
}

// 处理图片移除
function handleRemove(file) {
  fileList.value = fileList.value.filter((item) => item !== file)
}

// 发布
function add() {
  console.log('当前 fileList:', fileList.value)

  // 获取图片列表（如果上传过）
  let imgs = fileList.value.map((v) => {
    return v.response ? v.response.fileUrl : v.url
  })

  console.log('最终提交的图片:', imgs)

  addRequest(category.value, name.value, link.value, url.value, desc.value, coverImage.value)
    .then((response) => {
      console.log('提交成功:', response.data)

      // 清空表单数据
      category.value = ''
      name.value = ''
      desc.value = ''
      link.value = ''
      url.value = ''
      coverImage.value = ''
      fileList.value = []
    })
    .catch((error) => {
      console.error('提交失败:', error)
    })
}
</script>

<style lang="css" scoped>
.center {
  width: 550px;
  margin: 0 auto;
}
.btn {
  width: 150px;
}
.ipt1,
.ipt2 {
  margin-top: 10px;
}
#img {
  margin-top: 10px;
}
</style>
